package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import javax.swing.JTable;
import Controller.CompanyManagerController;
import Controller.DBcontroller;
import Entity.Complaint;
import Entity.Request;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
import javax.swing.JScrollPane;
/**
 * this is the GUI for approving request for changing rates. the company manager will select from the table of parking lots the request and aprrove or deny it.
 * @author Moran Abilea
 *
 */
public class ApproveRequestForChangingRatesGUI extends JPanel {

	private JTextField oldOccasional;
	private JTextField newOccasional;
	private JTextField parkingLotText;
	private JTextField oldOrdered;
	private JTextField newOrdered;
	private JTable table;
	private JTextField submitDate;
	JFrame frame;
	JPanel lastPanel;
	public void setLastPanel (JPanel panel)
	{
		this.lastPanel=panel;
	}
	public void setFrame (JFrame frame)
	{
		this.frame=frame;
	}
	
	private boolean canhandle=true;
	private boolean okflag;
	private Date mydate=new Date();
	private int row=-1;
	private boolean approvalflag=false;
	private boolean denyflag=false;

	/**
	 * Launch the application.
	 */
	//public static void main(String[] args) {
	//	EventQueue.invokeLater(new Runnable() {
	//		public void run() {
	//			try {
	//				ApproveRequestForChangingRatesGUI frame = new ApproveRequestForChangingRatesGUI();
	//				frame.setVisible(true);
	//			} catch (Exception e) {
	//				e.printStackTrace();
	//			}
	//		}
	//	});
	//}

	/**
	 * is the constructor. we have listers for the row selection in the table and radio boxes for approve or deny.
	 */
	public ApproveRequestForChangingRatesGUI() {
		
		final Request [] copy =CompanyManagerController.getRequestsforChangingRates();
		

		setBounds(100, 100, 918, 403);
		setBorder(new EmptyBorder(5, 5, 5, 5));
		setLayout(null);
		
		JLabel lblApprovedenyRequestsFor = new JLabel("Approve/Deny Requests for Changing Rates");
		lblApprovedenyRequestsFor.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblApprovedenyRequestsFor.setBounds(160, 11, 300, 17);
		add(lblApprovedenyRequestsFor);
		
		JLabel lblParkingLotNumber = new JLabel("Parking Lot Number:");
		lblParkingLotNumber.setBounds(10, 45, 138, 14);
		add(lblParkingLotNumber);
		
		parkingLotText = new JTextField();
		parkingLotText.setBounds(158, 39, 36, 20);
		add(parkingLotText);
		parkingLotText.setColumns(10);
		parkingLotText.setEditable(false);
		
		JLabel lblNewLabel = new JLabel("old Occasional Parking Place price:");
		lblNewLabel.setBounds(10, 70, 217, 14);
		add(lblNewLabel);
		
		oldOccasional = new JTextField();
		oldOccasional.setBounds(237, 67, 86, 20);
		add(oldOccasional);
		oldOccasional.setColumns(10);
		oldOccasional.setEditable(false);
		
		JLabel lblNewOccasionalParking = new JLabel("new Occasional Parking Place price:");
		lblNewOccasionalParking.setBounds(10, 95, 217, 14);
		add(lblNewOccasionalParking);
		
		newOccasional = new JTextField();
		newOccasional.setBounds(237, 92, 86, 20);
		add(newOccasional);
		newOccasional.setColumns(10);
		newOccasional.setEditable(false);
		
		JLabel lblOldOrderedParking = new JLabel("old Ordered Parking Place price:");
		lblOldOrderedParking.setBounds(10, 123, 217, 14);
		add(lblOldOrderedParking);
		
		oldOrdered = new JTextField();
		oldOrdered.setColumns(10);
		oldOrdered.setBounds(237, 120, 86, 20);
		add(oldOrdered);
		oldOrdered.setEditable(false);
		
		JLabel lblNewOrderedParking = new JLabel("new Ordered Parking Place price:");
		lblNewOrderedParking.setBounds(10, 148, 217, 14);
		add(lblNewOrderedParking);
		
		newOrdered = new JTextField();
		newOrdered.setColumns(10);
		newOrdered.setBounds(237, 145, 86, 20);
		add(newOrdered);
		newOrdered.setEditable(false);
		
		JLabel lblDateOfSubmission = new JLabel("Date of Submission:");
		lblDateOfSubmission.setBounds(10, 172, 164, 14);
		add(lblDateOfSubmission);
		
		submitDate = new JTextField();
		submitDate.setBounds(175, 169, 148, 20);
		add(submitDate);
		submitDate.setColumns(10);
		submitDate.setEditable(false);
		
		final JRadioButton rdbtnApprove = new JRadioButton("Approve Request");
		rdbtnApprove.setBounds(10, 193, 138, 23);
		add(rdbtnApprove);
		
		final JRadioButton rdbtnDeny = new JRadioButton("Deny Request");
		rdbtnDeny.setBounds(175, 193, 109, 23);
		add(rdbtnDeny);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(333, 83, 559, 126);
		add(scrollPane);
		
		table = new JTable(new approvalTable(CompanyManagerController.getRequestsforChangingRates()));
		scrollPane.setViewportView(table);
		
		// handle the functionality for clicking the row and "pour" it into Jtextfields.
		table.addMouseListener(new MouseAdapter() {
			  public void mouseClicked(MouseEvent e) {
			    if (e.getClickCount() == 2) {
			      JTable target = (JTable)e.getSource();
			      row = target.getSelectedRow();
			      parkingLotText.setText(Integer.toString(copy[row].getParkingLotNumber()+1));
			      oldOccasional.setText(Double.toString(DBcontroller.getCurrentPrices(copy[row].getParkingLotNumber()).getOccasionalParkingPlace()));
			      newOccasional.setText(Double.toString(copy[row].getChangePrices().getOccasionalParkingPlace()));
			      oldOrdered.setText(Double.toString(DBcontroller.getCurrentPrices(copy[row].getParkingLotNumber()).getOrderedParkingPlace()));
			      newOrdered.setText(Double.toString(copy[row].getChangePrices().getOrderedParkingPlace()));
			      submitDate.setText(copy[row].getChangePrices().getDateOfSubmission().toString());
			      if(copy[row].isAskedForChange()==false)
			    	  canhandle=false;
			      else
			    	  canhandle=true;
			    }
			  }
		});
		
		// handle checking V in approve.
		rdbtnApprove.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				rdbtnDeny.setSelected(false);
				// continue (don't forget to throw pop up in order to make sure the manager approve/deny every request.
				approvalflag=true;
			}
		});
		
		// handle checking V in deny.
		rdbtnDeny.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				rdbtnApprove.setSelected(false);
				// continue (don't forget to throw pop up in order to make sure the manager approve/deny every request.
				denyflag=true;
			}
		});
		
		JButton btnSaveRequestdumpRequest = new JButton("Save Request/Dump Request");
		btnSaveRequestdumpRequest.addActionListener(new ActionListener() {
		
			public void actionPerformed(ActionEvent arg0) {
				if(row==-1){
					JOptionPane needv=new JOptionPane();
					String errmsg="You didn't choose any request to approve or deny\n please select your request first.";
					needv.setMessage(errmsg);
					needv.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=needv.createDialog(null,"Error! Request wasn't selected.");
					iddidalog.setVisible(true);
				}	
				else if(!canhandle){
					JOptionPane needv=new JOptionPane();
					String errmsg="You can't handle a request which not requested!\n please choose another one.";
					needv.setMessage(errmsg);
					needv.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=needv.createDialog(null,"Error! Request wasn't found.");
					iddidalog.setVisible(true);
				}
				else if(!rdbtnApprove.isSelected()&&!rdbtnDeny.isSelected()){
					JOptionPane needv=new JOptionPane();
					String errmsg="You didn't choose approve or deny for this chosen parking lot request:"+Integer.toString(copy[row].getParkingLotNumber()+1);
					needv.setMessage(errmsg);
					needv.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=needv.createDialog(null,"Error! Option wasn't selected.");
					iddidalog.setVisible(true);
				}
				else if(rdbtnApprove.isSelected()&&rdbtnDeny.isSelected()){
					JOptionPane needv=new JOptionPane();
					String errmsg="You chose both approve and deny for this chosen parking lot request:"+Integer.toString(copy[row].getParkingLotNumber()+1)+"\n please select only one option.";
					needv.setMessage(errmsg);
					needv.setMessageType(JOptionPane.ERROR_MESSAGE);
					JDialog iddidalog=needv.createDialog(null,"Error! Both options selected.");
					iddidalog.setVisible(true);
				}
				else {
					JOptionPane needv=new JOptionPane();
					String okmsg="The new prices will be changed. saving to DB...";
					needv.setMessage(okmsg);
					needv.setMessageType(JOptionPane.INFORMATION_MESSAGE);
					JDialog iddidalog=needv.createDialog(null,"Saving...");
					iddidalog.setVisible(true);
					okflag=true;
					if((approvalflag&&!denyflag)||(!approvalflag&&denyflag)){ // if the request approved then save it to the DB. (don't forget to delete it from the request table in the DB)
						copy[row].setApprovedOrdenied(true);
					}
				}
			}
		});
		
		// if everything ok check what to do.
		if(okflag){
			if(approvalflag&&!denyflag){ // if the request approved then save it to the DB. (don't forget to delete it from the request table in the DB)
				copy[row].getChangePrices().setNewPrices(copy[row].getParkingLotNumber(),Double.parseDouble(newOccasional.getText()),Double.parseDouble(newOrdered.getText())); // calculate the new prices.
				copy[row].getChangePrices().save();
				DBcontroller.deleteRequestSQL(copy[row].getParkingLotNumber(), new Date()); //(the date is munfatz-change it!!!) making sure the request will be deleted from the DB.
			}
			else if(!approvalflag&&denyflag) // if the request denied then only delete it from the DB.
				DBcontroller.deleteRequestSQL(copy[row].getParkingLotNumber(),copy[row].getChangePrices().getDateOfSubmission()); // making sure the request will be deleted from the DB.
		}
		btnSaveRequestdumpRequest.setBounds(36, 257, 220, 23);
		add(btnSaveRequestdumpRequest);
		
		JLabel lblAfterSelectingApprovedeny = new JLabel("2. after selecting approve/deny click here");
		lblAfterSelectingApprovedeny.setBounds(41, 283, 243, 14);
		add(lblAfterSelectingApprovedeny);
		
		JLabel lblDateOfApproval = new JLabel("Date of Approval:"+mydate.toString());
		lblDateOfApproval.setBounds(24, 223, 246, 14);
		add(lblDateOfApproval);
		
		JLabel lblPleaseSelect = new JLabel("1. please select the request that you want to approve/deny. ");
		lblPleaseSelect.setBounds(351, 45, 338, 14);
		add(lblPleaseSelect);
				
		JButton btnCancelgoBack = new JButton("Cancel/go back");
		btnCancelgoBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frame.setContentPane((JPanel)lastPanel);
			}
		});
		btnCancelgoBack.setBounds(37, 306, 129, 23);
		add(btnCancelgoBack);
		
		JLabel lblAfterClickingSave = new JLabel("after clicking save or if you want to cancel click here");
		lblAfterClickingSave.setBounds(37, 340, 308, 14);
		add(lblAfterClickingSave);
		
		JLabel lblRememberIfThe = new JLabel("remember if the parking lot didn't request for change you can't handle it.");
		lblRememberIfThe.setBounds(351, 58, 424, 14);
		add(lblRememberIfThe);

	}
}

class approvalTable extends AbstractTableModel
{
	String[] titles={"Parking Lot Number","New Occasional Price","New Ordered Price","Requested for Changing?","Date of Submission","Approved or denied?"};
	Object[][] data;
	
	public approvalTable(Request[] r)
	{
		super();
		this.data=new Object[r.length][6];
		for(int i=0; i<r.length; i++)
		{
			this.data[i][0]=r[i].getParkingLotNumber()+1;
			this.data[i][1]=r[i].getChangePrices().getOccasionalParkingPlace();
			this.data[i][2]=r[i].getChangePrices().getOrderedParkingPlace();
			if(r[i].isAskedForChange()) this.data[i][3]="Yes";
			else this.data[i][3]="No";
			this.data[i][4]=r[i].getChangePrices().getDateOfSubmission();
			if(!r[i].isApprovedOrdenied()) this.data[i][5]="Not yet";
			else this.data[i][5]="Already approved or denied";
		}
	}
	// override the other function.
	@Override
	public int getColumnCount() {return this.titles.length;}

	@Override
	public int getRowCount() {return data.length;}

	@Override
	public Object getValueAt(int arg0, int arg1) {return data[arg0][arg1];}
	
	@Override
	public String getColumnName(int column) {return (String) this.titles[column];}
	
}